package com.iflytek.controller;

import com.github.pagehelper.PageInfo;
import com.iflytek.entity.Administrator;
import com.iflytek.query.AdministratorQuery;
import com.iflytek.service.AdministratorService;
import com.iflytek.utils.ResultUtil;
import com.iflytek.vo.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Map;

@Controller
@RequestMapping("back/admin")
public class AdministratorController {

    @Autowired
    private AdministratorService administratorService;

    @GetMapping("/list")
    public String list() {
        return "admin/list";
    }

    @ResponseBody
    @GetMapping("/listData")
    public ResultData listData(AdministratorQuery query, Integer pageName, Integer pageSize) {
        System.out.println(query);
        PageInfo<Administrator> pageInfo = administratorService.getAllAdministratorList(query, pageName, pageSize);
        return ResultUtil.success(pageInfo.getTotal(), pageInfo.getList());
    }

    @GetMapping("/add")
    public String addUI() {
        return "admin/add";
    }

    @ResponseBody
    @PostMapping("/add")
    public Map<String, Object> add(Administrator administrator) {
        int save = administratorService.saveAdministrator(administrator);
        return ResultUtil.resultMap(save);
    }

    @GetMapping("/edit")
    public String editUI(Integer id, Model model) {
        model.addAttribute("admin", administratorService.getById(id));
        return "admin/edit";
    }

    @ResponseBody
    @PostMapping("/edit")
    public Map<String, Object> edit(Administrator administrator) {
        int update = administratorService.updateMsgById(administrator);
        return ResultUtil.resultMap(update);
    }

    @ResponseBody
    @PostMapping("/delete")
    public Map<String, Object> delete(Integer administratorId) {
        int delete = administratorService.deleteById(administratorId);
        return ResultUtil.resultMap(delete);
    }

    @ResponseBody
    @PostMapping("/batchDelete")
    public Map<String, Object> batchDelete(String ids) {
        int batchByDel = administratorService.delBatchByIds(Arrays.asList(ids.split(",")));
        return ResultUtil.resultMap(batchByDel);
    }
}
